package com.example.waterdispenserm2.mo.inductionmain;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.Toast;
import com.example.waterdispenserm2.R;
import com.example.waterdispenserm2.base.BasicsActivity;
import com.example.waterdispenserm2.databinding.ActivityInductionCookerBinding;

import java.util.HashMap;
import java.util.Map;

public class InductionCookerActivity extends BasicsActivity<ActivityInductionCookerBinding> {

    private SerialPortHelper serialPort;
    // 功能按钮映射
    private Map<Integer, String> functionMap = new HashMap<>();
    private int currentFunction = -1;


    // 数码管显示
    private int digit1 = 0, digit2 = 0, digit3 = 0, digit4 = 0;
    private int timerMinutes = 0;
    @Override
    public void widgetClick(View v) {

    }

    @Override
    public void setListener() {

    }

    @Override
    public void initView() {
        // 初始化功能映射
        initFunctionMap();
        // 初始化UI
        initUI();


        if (!TextUtils.isEmpty(binding.etAdd.getText().toString().trim())) {
            // 绑定服务
            binding.btOpen.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String path="/dev/ttyS0";
                    if ("0".equals(binding.etAdd.getText().toString().trim())) {
                        path="/dev/ttyS0";
                    } else if ("1".equals(binding.etAdd.getText().toString().trim())) {
                        path="/dev/ttyS1";
                    } else if ("2".equals(binding.etAdd.getText().toString().trim())) {
                        path="/dev/ttyS2";
                    } else if ("3".equals(binding.etAdd.getText().toString().trim())) {
                        path="/dev/ttyS3";
                    } else if ("4".equals(binding.etAdd.getText().toString().trim())) {
                        path="/dev/ttyS4";
                    } else if ("5".equals(binding.etAdd.getText().toString().trim())) {
                        path="/dev/ttyS5";
                    } else if ("6".equals(binding.etAdd.getText().toString().trim())) {
                        path="/dev/ttyS6";
                    } else if ("7".equals(binding.etAdd.getText().toString().trim())) {
                        path="/dev/ttyS7";
                    }
                    open(path);
                }
            });
        }
        // 初始显示
        if (isOpen) {
            updateDisplay();
        }


        binding.btClase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onDestroy();
            }
        });

        binding.ivMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    boolean isOpen;
    private void open(String path){
        // 初始化串口
        serialPort = new SerialPortHelper(data -> {
            int keyValue = InductionCookerProtocol.parseKeyData(data);
            runOnUiThread(() -> handleKeyPress(keyValue));
        });

        // 打开串口 (根据实际设备修改路径和波特率)
        isOpen=serialPort.open(path, 9600);

        if (isOpen) {
            Toast.makeText(InductionCookerActivity.this, "状态: 已连接", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(InductionCookerActivity.this, "串口打开失败", Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    protected ActivityInductionCookerBinding getViewBinding() {
        return ActivityInductionCookerBinding.inflate(LayoutInflater.from(this));
    }

    private void initFunctionMap() {
        functionMap.put(0, "煲汤");
        functionMap.put(1, "蒸煮");
        functionMap.put(2, "烧水");
        functionMap.put(3, "文火");
        functionMap.put(4, "武火");
        functionMap.put(5, "火锅");
        functionMap.put(6, "煲粥");
        functionMap.put(7, "炒菜");
    }
    private void initUI() {

        // 初始化功能按钮
        for (int i = 0; i < 8; i++) {
            Button btn = new Button(this);
            btn.setId(View.generateViewId());
            btn.setText(functionMap.get(i));
            btn.setTextColor(Color.parseColor("#ffffff"));
            btn.setBackgroundResource(R.drawable.btn_function_bg);
            btn.setTag(i);

            // 设置按钮大小
            int size = (int) (getResources().getDisplayMetrics().density * 100);
            GridLayout.LayoutParams params = new GridLayout.LayoutParams();
            params.width = size;
            params.height = size;
            params.setMargins(20, 20, 20, 20);
            btn.setLayoutParams(params);

            final int function = i;
            btn.setOnClickListener(v -> toggleFunction(function));
            binding.gridFunctions.addView(btn);
        }

        // 设置按钮点击事件
        binding.btnPower.setOnClickListener(v -> handleKeyPress(0)); // 无按键
        binding.btnTimer.setOnClickListener(v -> handleKeyPress(1)); // 定时
        binding.btnMinus.setOnClickListener(v -> {
            adjustTime(-1);
            handleKeyPress(3); // 减
        });
        binding.btnPlus.setOnClickListener(v -> {
            adjustTime(1);
            handleKeyPress(4); // 加
        });
        binding.btnFunction.setOnClickListener(v -> handleKeyPress(5)); // 功能
        binding.btnStart.setOnClickListener(v -> handleKeyPress(6)); // 启动

        // 设置数码管样式
        binding.tvDisplay.setTextSize(32);
        binding.tvDisplay.setTextColor(Color.parseColor("#FF5722"));
        binding.tvDisplay.setBackgroundResource(R.drawable.display_bg);

        binding.tvTimeDisplay.setTextSize(24);
        binding.tvTimeDisplay.setTextColor(Color.WHITE);
    }


    @SuppressLint("SetTextI18n")
    private void toggleFunction(int function) {
        currentFunction = (currentFunction == function) ? -1 : function;
        updateDisplay();

        // 更新LED状态
        int ledState = (currentFunction != -1) ? (1 << currentFunction) : 0;
        byte[] data = InductionCookerProtocol.buildDisplayData(digit1, digit2, digit3, digit4, ledState);
        if (isOpen){
            serialPort.sendData(data);
        }else {
            Toast.makeText(InductionCookerActivity.this,"串口未连接",Toast.LENGTH_SHORT).show();
        }

        // 显示当前功能
        if (currentFunction != -1) {
            binding.tvKeyStatus.setText("当前功能: " + functionMap.get(currentFunction));
        } else {
            binding.tvKeyStatus.setText("请选择功能");
        }
    }

    private void adjustTime(int minutes) {
        timerMinutes += minutes;
        if (timerMinutes < 0) timerMinutes = 0;
        if (timerMinutes > 9999) timerMinutes = 9999;

        // 分解为4位数字
        digit1 = timerMinutes / 1000;
        digit2 = (timerMinutes % 1000) / 100;
        digit3 = (timerMinutes % 100) / 10;
        digit4 = timerMinutes % 10;

        updateDisplay();
    }

    private void updateDisplay() {
        // 更新数码管显示
        String display = String.format("%d%d%d%d", digit1, digit2, digit3, digit4);
        binding.tvDisplay.setText(display);

        // 更新时间显示
        binding.tvTimeDisplay.setText(String.format("%02d:%02d", timerMinutes / 60, timerMinutes % 60));

        // 发送显示数据
        int ledState = (currentFunction != -1) ? (1 << currentFunction) : 0;
        byte[] data = InductionCookerProtocol.buildDisplayData(digit1, digit2, digit3, digit4, ledState);
        if (isOpen){
            serialPort.sendData(data);
        }else {
            Toast.makeText(InductionCookerActivity.this,"串口未连接",Toast.LENGTH_SHORT).show();
        }
    }

    private void handleKeyPress(int keyValue) {
        String[] keyNames = {"电源", "定时/预约", "电量/电压", "减", "加", "功能", "启动"};

        if (keyValue < keyNames.length) {
            String action = "按键: " + keyNames[keyValue];

            // 特殊按键处理
            switch (keyValue) {
                case 0: // 电源
                    resetCooker();
                    break;
                case 6: // 启动
                    startCooking();
                    break;
            }

            binding.tvKeyStatus.setText(action);
        }
    }

    private void resetCooker() {
        digit1 = digit2 = digit3 = digit4 = 0;
        timerMinutes = 0;
        currentFunction = -1;
        updateDisplay();
        binding.tvKeyStatus.setText("已重置");
    }

    private void startCooking() {
        if (currentFunction == -1) {
            binding.tvKeyStatus.setText("请先选择功能");
            return;
        }

        if (timerMinutes == 0) {
            binding.tvKeyStatus.setText("请设置时间");
            return;
        }

        binding.tvKeyStatus.setText("开始烹饪: " + functionMap.get(currentFunction));
        // 这里可以添加实际的烹饪启动逻辑
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (serialPort != null) {
            serialPort.close();
        }
    }
}